import { defineStore } from "pinia";

export const useCart = defineStore("Cart", {
  state() {
    return {
      cartData: [],
    };
  },
  getters: {
    total() {
      let total = this.cartData
        .reduce((total, item) => {
          return (total += item.price * item.count);
        }, 0)
        .toFixed(2);
      return total;
    },
  },
  actions: {
    //添加
    ADD_CART(payload) {
      let target = this.cartData.find((item) => item.id === payload.id);
      if (!target) {
        let obj = {
          id: payload.id,
          title: payload.title,
          count: 1,
          price: payload.price,
        };
        this.cartData.push(obj);
      } else {
        target.count++;
      }
    },

    DEL_CART(i) {
      // 删除
      let target = this.cartData.find((item) => {
        if (item.id === i.id && item.count > 0) {
          item.count = item.count - 1;
        }
        return item;
      });
      // 数据为0时，全部删掉
      if (target.count === 0) {
        this.cartData = this.cartData.filter((item) => item.id !== target.id);
      }
    },
  },
});
